package com.example.xinli.interceptor;

import com.example.xinli.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component   //在容器中进行注册
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            System.out.println("OPTIONS请求，放行");
            return true;
        }

        //暂时放行全部
//        return true;

        //0924暂时注释
        String token = request.getHeader("Authorization");
        if(token != null) {
            token = token.split(" ")[1];
        }
        if(TokenUtil.verify(token)) {
            Boolean isExpire = Boolean.FALSE.equals(redisTemplate.hasKey("user:" + token));
            log.info("是否放行"+!isExpire);
            return !isExpire;
        }

        // 失败我们跳转回登录页面
//        request.setAttribute("msg","登录出错");
//        request.getRemoteHost();
//        request.getRequestDispatcher("/loginByWechat").forward(request,response);

        //0924暂时注释

        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        return false;
    }

}
